import { WebSocket } from "ws";
import { User } from "../../../types/User";
import { roomsTable } from "../../../database/rooms-table";
import { conversionMessage } from "../helpers/message-converter";
import { ViewDiscardCardsMessageData } from "../types/MessageData";
import { Card } from "../../../types/Card";

export const viewDiscardCardsHandler = ({ user, payload }: { client: WebSocket; user: User; payload: ViewDiscardCardsMessageData["payload"] }) => {
	const room = roomsTable.rooms.find((v) => v.roomId == payload.roomId);
	const player = room?.players.find((v) => v.user.userId == user.userId);
	if (room && player) {
		const selectedCards = payload.cardIds.map((v) => room.discardCards.find((v2) => v2.cardId === v)).filter((v) => v) as Card[];
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "viewedDiscardCards", payload: { roomId: room.roomId, userId: user.userId, cards: selectedCards } })));
		const log = { userId: user.userId, username: user.username, log: "查看了弃牌堆的" + selectedCards.length + "张牌。" };
		room.logs.push(log);
		room.players.forEach((v) => v.client!.send(conversionMessage({ type: "roomLog", payload: log })));
	}
};
